package cn.lijia.itrip.controller;

import cn.lijia.itrip.common.DigestUtil;
import cn.lijia.itrip.common.Dto;
import cn.lijia.itrip.common.DtoUtil;
import cn.lijia.itrip.common.ErrorCode;
import cn.lijia.itrip.exception.ItripException;
import cn.lijia.itrip.model.ItripUser;
import cn.lijia.itrip.service.ItripUserService;
import cn.lijia.itrip.service.TokenService;
import cn.lijia.itrip.vo.LoginResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static sun.net.www.protocol.http.HttpURLConnection.userAgent;

/**
 * @author 李嘉
 * @create 2018-08-30-8:59
 */
@Controller
@RequestMapping("/api")
public class LoginController {

    @Resource
    private ItripUserService itripUserService;

    @Resource
    private TokenService tokenService;

    //登录
    @RequestMapping(value = "/dologin",method = RequestMethod.POST)
    @ResponseBody
    public Dto doLogin(String name, String password, HttpServletRequest request){
        //验证用户账号密码
        try {
            ItripUser itripUser = itripUserService.login(name, password);
            //登录成功
            String userAgent = request.getHeader("user-agent");
            //构建token
            String token = tokenService.generateToken(itripUser, userAgent);

            tokenService.saveToken(token,itripUser);
            //返回数据
            long genTime = System.currentTimeMillis(); //构建时间
            long expTime = genTime + (1000 * 60 * 60 * 2);//过期时间
            return DtoUtil.returnDataSuccess(new LoginResultVO(token,genTime,expTime));

        } catch (ItripException e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(),e.getErrorCode());
        }catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("登录失败", ErrorCode.AUTH_LOGIN_FAILURE);
        }

    }


    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    @ResponseBody
    public Dto logout(HttpServletRequest request){
        //获取token
        String token = request.getHeader("token");
        String userAgent = request.getHeader("user-agent");
        if (!tokenService.validateToken(token,userAgent)) {
            return DtoUtil.returnFail("Token无效",ErrorCode.AUTH_TOKEN_INVALID);
        }
        //退出
        tokenService.del(token);
        //返回退出成功
        return DtoUtil.returnSuccess("注销成功");
    }


}
